//
// Created by cmz2000 on 2021/8/4.
//

#include "main.h"

int getTable(char *path) {
    printf("getting DNS table...\n");

    char table[AMOUNT][2 * LENGTH + 1];
    FILE *fp = NULL;
    if ((fp = fopen(path, "r")) == NULL) {
        printf("Can not open DNS table...\n");
        exit(1);
    }

    int row = 0;
    // 每次读入一行
    while (fgets(table[row], 2 * LENGTH + 1, fp)) {
        row++;
        if (row == AMOUNT) {
            printf("DNS table is too large...\n");
            break;
        }
    }
    // 对每一行, 划分IP和域名
    for (int i = 0; i < row; i++) {
        int pos1, pos2;//pos1为空格的位置, 分隔开IP和域名; pos2为换行符
        for (int j = 0; j < 2 + LENGTH + 1; j++) {
            if (table[i][j] == ' ')
                pos1 = j;
            else if (table[i][j] == '\n') {
                pos2 = j;
                break;
            }
        }
        memcpy(DNS_table[i].ip, table[i], pos1);
        memcpy(DNS_table[i].domain, table[i] + pos1 + 1, pos2 - pos1 - 1);
    }

    printf("read DNS table success! %d in total", row);
    fclose(fp);
    return row;
}